const WebSocket = require('ws');

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 6060 });

// 记录连接的客户端
let clients = [];

// 处理客户端连接
wss.on('connection', (ws) => {
    console.log('A new client connected');
    clients.push(ws);

    // 发送欢迎消息
    ws.send(JSON.stringify({ type: 'message', content: 'Welcome to the chat room!' }));

    // 心跳检测
    let heartBeatInterval = setInterval(() => {
        ws.ping(); // 向客户端发送 ping 消息
    }, 30000); // 每 30 秒发送一次 ping

    // 监听客户端消息
    ws.on('message', (message) => {
        console.log('Received:', message);
        // 广播消息给其他所有客户端
        clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    // 监听客户端关闭
    ws.on('close', () => {
        console.log('A client disconnected');
        clearInterval(heartBeatInterval); // 清除心跳检测
        clients = clients.filter(client => client !== ws); // 移除断开连接的客户端
    });

    // 监听错误
    ws.on('error', (err) => {
        console.error('WebSocket error:', err);
    });
});

console.log('WebSocket server started on ws://localhost:6060');